goog.provide('tipfy.ui.superRatings');
goog.provide('tipfy.ui.ratings');

goog.require('tipfy');
goog.require('tipfy.XhrIo');

goog.require('goog.events');
goog.require('goog.ui.Component');
goog.require('goog.ui.Ratings');


tipfy.ui.ratings = function(url, container_id, initial_value) {
    var el = document.getElementById(container_id),
        select = el.getElementsByTagName('select')[0],
        label = el.getElementsByTagName('label')[0],
        ratings = new goog.ui.Ratings(),
        default_text = label.innerHTML,
        current_text = default_text,
        changed = false;

    goog.events.listen(ratings, 'change', function(e) {
        var value = select.options[e.target.getSelectedIndex()].getAttribute('value');

        current_text = e.target.getValue() || default_text;
        label.innerHTML = current_text;

        if(changed) {
            tipfy.XhrIo.send(url, function() {
                var body = this.getResponseJson().body;
                alert(body);
            }, 'POST', 'rating=' + value);
        }
    });

    goog.events.listen(ratings, 'highlightchange', function(e) {
        changed = true;
        label.innerHTML = e.target.getHighlightedValue() || current_text;
    });

    ratings.decorate(el);
    ratings.setSelectedIndex(initial_value || 0);
}
